import { Card, Form, Input, Modal, Spin } from 'antd';
import React, { useContext, useRef, useState } from 'react';
import { useBoolean } from 'ahooks';
import PubSub from 'pubsub-js';
import FlowContext from '@/pages/Flow/FlowContext';
import request from '@/utils/request';
import VersionPageTable from '../../VersionPageTable';
import useModal from '@/hooks/UseModal';
import InvocationConfig from '@/pages/Invocation/InvocationConfig';

function InvocationPanel({ form, node, update }) {
  const { getFieldDecorator, validateFields } = form;
  const {
    label: invocationName,
    nodeCode: invocationCode,
    nodeId: invocationId,
    nodeVersionId,
  } = node;

  // 全局Context
  const {
    state: { processId, versionId, readOnly },
  } = useContext(FlowContext);

  // 页面Loading
  const [loading, setLoading] = useState(false);

  // 编辑状态控制
  const isEdit = !!invocationId;
  const [editDisabled, { setFalse: enableEdit, setTrue: disableEdit }] = useBoolean(isEdit);

  // 弹窗配置
  const { visible, data, showModal, hideModal } = useModal();

  // 保存表单
  function save() {
    validateFields((err, data) => {
      if (err) {
        return;
      }

      setLoading(true);
      if (isEdit) {
        request
          .post(`/invocation/updateInvocation`, { data })
          .then(() => {
            update({
              label: data.invocationName,
              nodeCode: data.invocationCode,
            });
            disableEdit();
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
          })
          .finally(() => {
            setLoading(false);
          });
      } else {
        request
          .post(`/invocation/createInvocation`, { data })
          .then(({ invocationId }) => {
            update({
              nodeId: invocationId,
              label: data.invocationName,
              nodeCode: data.invocationCode,
            });
            disableEdit();
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  }

  function renderExtra() {
    if (readOnly) {
      return null;
    }
    return editDisabled ? <a onClick={enableEdit}>编辑</a> : <a onClick={save}>保存</a>;
  }

  function renderForm() {
    return (
      <Form>
        <Form.Item>
          {getFieldDecorator('invocationId', {
            initialValue: invocationId,
          })(<Input hidden />)}
        </Form.Item>
        <Form.Item label="调用名称">
          {getFieldDecorator('invocationName', {
            initialValue: invocationName,
            rules: [
              {
                required: true,
                message: '调用名称不能为空',
              },
            ],
          })(<Input disabled={editDisabled} placeholder="请输入" />)}
        </Form.Item>
        <Form.Item label="调用编码">
          {getFieldDecorator('invocationCode', {
            initialValue: invocationCode,
            rules: [
              {
                required: true,
                message: '调用编码不能为空',
              },
            ],
          })(<Input disabled={editDisabled} placeholder="请输入" />)}
        </Form.Item>
      </Form>
    );
  }

  const versionTableRef = useRef();

  function renderVersionList() {
    if (!isEdit) {
      return null;
    }
    return (
      <VersionPageTable
        ref={versionTableRef}
        style={{ marginTop: '16px' }}
        element="invocation"
        elementIdKey="invocationId"
        elementId={invocationId}
        elementVersionId={nodeVersionId}
        onClickConfig={({ elementId, versionId, readOnly }) => {
          showModal({ invocationId: elementId, versionId, readOnly });
        }}
        readOnly={readOnly}
        onValidVersion={nodeVersionId => {
          update({ nodeVersionId });
          PubSub.publish(`nodeSave_${processId}_${versionId}`);
        }}
      />
    );
  }

  return (
    <Card size="small" title="本地调用" bordered={false} extra={renderExtra()}>
      <Spin spinning={loading}>
        {renderForm()}
        {renderVersionList()}
      </Spin>
      <Modal
        width={650}
        title="本地调用"
        visible={visible}
        onCancel={hideModal}
        destroyOnClose
        footer={null}
      >
        <InvocationConfig
          {...data}
          onCancel={hideModal}
          onSaveAndValidVersion={() => {
            versionTableRef.current && versionTableRef.current.setCurrentVersionId(data.versionId);
            update({ nodeVersionId: data.versionId });
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
            versionTableRef.current && versionTableRef.current.refresh();
          }}
        />
      </Modal>
    </Card>
  );
}

export default Form.create()(InvocationPanel);
